<template>
  <div>
    <div class="app-page">
      <div class="main-config">
        <el-table-form ref="form">
          <el-form-item label="日期:" :table-form-merge="1">
            <el-date-picker
              v-model="date"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-button v-permission="[110202,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-table-form>
        <div style="margin-bottom: 10px;">
          <div>
            <el-button v-permission="[110202,2]" type="primary" icon="el-icon-circle-plus" @click="add">新增</el-button>
          </div>
        </div>
        <el-table ref="lbTable" v-loading="$loadingPlugin.getConfigData" class="table-list" :data="tableData" border @select="dialogCheck" @selection-change="dialogCheck1" @row-click="cellSelect">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="名称" width="100" :show-overflow-tooltip="true" prop="goodsName" align="center">
            <template slot-scope="scoped">
              <div @click="noEdit(scoped.row)">{{ scoped.row.goodsName }}</div>
            </template>
          </el-table-column>
          <el-table-column v-for="(item,index) in timePeriod" :key="index" prop="" :label="item.start+'~'+item.end" min-width="110" align="center">
            <template slot-scope="scoped">
              <el-input-number v-show="scoped.row.isEdit" v-model.number="scoped.row['total'+index]" class="count" :controls="false" oninput="value=value.replace(/[^\d]/g,'')" :min="0" />
              <div v-show="!scoped.row.isEdit" @click="edit(scoped.row)">{{ scoped.row['total'+index] }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" label="09:00-10:00" width="100" align="center">
            <template slot-scope="scoped">
              <el-input v-show="scoped.row.isEdit" v-model.number="scoped.row.total2" oninput="value=value.replace(/[^\d]/g,'')" :max="399" :min="0">
                <template slot="suffix"><div style="line-height: 32px;" /></template>
              </el-input>
              <div v-show="!scoped.row.isEdit" @click="edit(scoped.row)">{{ scoped.row.total2 }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="10:00-11:00" width="100" align="center">
            <template slot-scope="scoped">
              <el-input v-show="scoped.row.isEdit" v-model.number="scoped.row.total3" oninput="value=value.replace(/[^\d]/g,'')" :max="399" :min="0">
                <template slot="suffix"><div style="line-height: 32px;" /></template>
              </el-input>
              <div v-show="!scoped.row.isEdit" @click="edit(scoped.row)">{{ scoped.row.total3 }}</div>
            </template>
          </el-table-column> -->

          <el-table-column v-if="isAfterToday" prop="" label="操作" align="center" width="50">
            <template slot-scope="scoped">
              <el-button v-permission="[110202,3]" type="text" @click="remove(scoped.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px;">
          <div>
            <el-button v-permission="[110202,4]" type="primary" icon="el-icon-circle-plus" :loading="$loadingPlugin.save" @click="save">保存配置</el-button>
          </div>
        </div>
      </div>
    </div>
    <add ref="add" :time-period="timePeriod" @updateList="getConfigData" />
  </div>
</template>

<script>
  import { accountopeningSave, queryOrderSetting, deleteOrderSetting, updateOrderSetting, appointTimeSettingQuery } from '@/api'
  import { parseTime } from '@/utils'
  import add from '../components/add.vue'
  import dayjs from 'dayjs'

  export default {
    name: 'bottlesConfig',
    components: {
      add
    },
    data() {
      return {
        parseTime,
        orgTreeData: [],
        date: parseTime(new Date(), '{y}-{m}-{d}'),
        tableData: [],
        selectioned: null,
        currentOrg: {},
        checkList: [],
        input1: '',
        input2: '',
        input3: '',
        isAfterToday: false,
        timePeriod: []
      }
    },

    created() {
      this.getTimePeriod()
    },
    methods: {
      async getTimePeriod() {
        const res = await appointTimeSettingQuery()
        if (res && res.data) {
          this.timePeriod = res.data.map((item) => ({
            ...item,
            start: dayjs(item.startTime).format('HH:mm'),
            end: dayjs(item.endTime).format('HH:mm')
          }))
        }
      },
      // 查询
      async search() {
        await this.getConfigData(this.currentOrg)
        this.isAfterToday = this.handleisAfterToday()
      },
      handleisAfterToday() {
        const date1 = dayjs(this.date)
        const date2 = dayjs(new Date())
        return date1.diff(date2) > 0
      },
      // 新增
      add() {
        this.$refs.add.open(this.currentOrg)
      },
      // 勾选
      async dialogCheck(selection, row) {
        this.$refs.lbTable.clearSelection()
        if (selection.length === 0) { // 判断selection是否有值存在
          return
        }
        if (row) {
          row.isEdit = true
          this.selectioned = row
          this.$refs.lbTable.toggleRowSelection(row, true)
        }
      },
      // 勾选变化时
      dialogCheck1(selection) {
        if (selection.length === 0) this.selectioned = null
      },
      // 编辑
      async edit(row) {
        await this.tableData.forEach(item => {
          item.isEdit = false
        })
        row.isEdit = true
      },
      // 编辑
      noEdit(row) {
        row.isEdit = false
      },
      // 保存
      async save() {
        console.log(this.selectioned)
        if (!this.selectioned) {
          this.$message.error('请先勾选数据')
          return
        }
        const row = this.selectioned
        const keyList = Object.keys(row).filter(item => item.includes('total'))
        const list = keyList.map((item, index) => ({
          orgId: row.orgId,
          happendDate: row.happendDate,
          showIndex: index + 1,
          goodsId: row.goodsId,
          total: row['total' + index],
          beginTime: this.timePeriod[index] && this.timePeriod[index].start,
          endTime: this.timePeriod[index] && this.timePeriod[index].end
        }))

        const res = await updateOrderSetting(list)
        if (res) {
          this.$notify({
            title: '提示',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.getConfigData(this.currentOrg)
        }
      },
      // 删除
      async remove(row) {
        console.log(row)
        const list = []
        let num = 0
        for (const val in row) {
          const item = {}
          if (val.indexOf('total') > -1) {
            num++
            item.orgId = row.orgId
            item.happendDate = row.happendDate
            item.showIndex = num
            item.goodsId = row.goodsId
            list.push(item)
          }
        }
        // console.log('list',list)
        this.$confirm('确定删除数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          deleteOrderSetting(list).then(res => {
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getConfigData(this.currentOrg)
          })
        })
      },
      async getConfigData(val) {
        this.currentOrg = val
        this.tableData = []
        const res = await queryOrderSetting({ orgId: this.currentOrg.orgId, happendDate: this.date })
        await res.data.forEach(element => {
          const box = {}
          for (const val in element) {
            // console.log(val)
            // console.log(element[val])
            box.name = val
            box.isEdit = false
            element[val].forEach((item, index) => {
              box['total' + index ] = item.total
              box.goodsId = item.goodsId
              box.goodsName = item.goodsName
              box.happendDate = item.happendDate
              box.orgId = item.orgId
            })
            this.tableData.push(box)
          }
        })
        // console.log(this.tableData)
      },
      saveConfig() {
        const paramInfo = {
          orgId: this.currentOrg.orgId,
          corpCode: this.currentOrg.corpCode,
          orgName: this.currentOrg.orgName,
          orgSNNo: this.currentOrg.orgSNNo,
          kilogram: this.input1,
          delivery: this.input2,
          range: this.input3
        }
        if (this.checkList.indexOf('公众号开户租瓶') > -1) {
          paramInfo.sp1 |= 1
        }
        if (this.checkList.indexOf('启用出入库强制还瓶') > -1) {
          paramInfo.sp1 |= 1 << 2
        }
        if (this.checkList.indexOf('启用<<供气主体变更确认书>>') > -1) {
          paramInfo.sp1 |= 1 << 3
        }
        if (this.checkList.indexOf('启用订单预约功能') > -1) {
          paramInfo.sp1 |= 1 << 4
        }
        if (this.checkList.indexOf('启用一户一码') > -1) {
          paramInfo.sp1 |= 1 << 6
        }
        accountopeningSave(paramInfo).then(res => {
          this.$message.success('保存成功')
        }).catch(() => {
          this.$message.error('保存失败')
        })
      },
      cellSelect(row, column) {
        this.$refs.lbTable.clearSelection()
        this.selectioned = row
        this.$refs.lbTable.toggleRowSelection(row, true)
      }
    }
  }
</script>

<style lang='scss' scoped>

  .main-config {
    margin: 20px;
    flex: 1;
    .table-list {
      width: calc(100vw - 540px);
      /deep/ .has-gutter {
        .el-checkbox {
          display: none;
        }
      }
    }
    .config-item {
      margin-bottom: 20px;
    }
  }
  /deep/ .el-divider--horizontal {
    margin: 8px 0;
  }

  .count {
    width: 100%;
  }

</style>
